﻿using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;
using Admin.IService;
using Admin.Model;
using Admin.Model.RequestModel;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace Admin.Web.Controllers.Api
{
    public class LoginController : ApiController
    {
        private ILoginService _loginService;
        public LoginController(ILoginService loginService)
        {
            _loginService = loginService;
        }

        [HttpPost]
        //[ValidateAntiForgeryToken]
        public async Task<InfoModel> Login([FromBody]RequestLogin login)
        {
            string Code = HttpContext.Session.GetString("LoginCaptcha");
            if (login.ValidateCode != Code)
                return OpReturn(0, "验证码错误！");

            SysUser user = await _loginService.Login(login.Account, login.Password);
            if (user != null)
            {
                #region 设置用户身份 写入cookie
                var claims = new List<Claim>()
            {
                new Claim(ClaimTypes.Name,user.Name),
                new Claim(ClaimTypes.NameIdentifier,user.Account)
            };
                var Identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
                Identity.AddClaims(claims);

                //init the identity instances 
                var userPrincipal = new ClaimsPrincipal(Identity);

                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, userPrincipal, new AuthenticationProperties
                {
                    ExpiresUtc = DateTimeOffset.Now.AddMinutes(60),
                    IsPersistent = true,
                    AllowRefresh = true
                });
                #endregion
                return OpReturn(1, "登陆成功！");
            }
            else
            {
                return OpReturn(0, "账号或密码错误！");
            }
        }
    }
}